import { Switch as AntdSwitch } from 'antd';
import { useState, useImperativeHandle } from 'react';
export function Switch(props: {onclick: () => boolean | Promise<boolean>, defaultCheck?: boolean, onValueChange?: (val: boolean) => void}) {
    let [loading, setLoading] = useState(false);
    let [ckecked, setChecked] = useState(props.defaultCheck == undefined || props.defaultCheck == false ? false : true);
    function click() {
        let result = props.onclick();
        if(typeof result == 'boolean') {
            setChecked(result);
            props.onValueChange !== undefined && props.onValueChange(result);
        } else {
            setLoading(true);
            result
            .then((res) => 
            {
                setChecked(res);
                props.onValueChange !== undefined && props.onValueChange(res);
            })
            .finally(() => setLoading(false));
        }
    }
    return (
        <span>
            <AntdSwitch 
            checked={ckecked}
            loading={loading}
            onClick = {click}
            />
        </span>

    );
}